const formatTime = (date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
};

const formatNumber = (n) => {
  const x = n.toString();
  return x[1] ? x : `0${x}`;
};

// 千分位
const formatNum = (value) => {
  if (!value && value !== 0) return 0;
  const str = value.toString();
  const reg = str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
  return str.replace(reg, '$1,');
};


/**
 * 节流
 * @param {Function} fun 执行目标func
 * @param {Number} delay 延迟时间
 */
const throttle = (fun, delay) => {
  let last;
  let deferTimer;
  return function (_args) {
    const that = this;
    const args = _args;
    const now = +new Date();
    if (last && now < last + delay) {
      clearTimeout(deferTimer);
      deferTimer = setTimeout(() => {
        last = now;
        fun.apply(that, args);
      }, delay);
    } else {
      last = now;
      fun.apply(that, args);
    }
  };
};
/**
 * 防抖
 * @param {Function} fn 执行目标func
 * @param {Number} delay 延迟时间
 */
const debounce = (fn, delay) => {
  let timer;
  return function (_args) {
    const that = this;
    const args = _args;
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.call(that, args);
    }, delay);
  };
};

module.exports = {
  formatTime,
  throttle,
  debounce,
  formatNum,
};
